package com.aihna.system.controller.system;

import java.util.List;
import java.util.stream.Collectors;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.aihna.common.idempotent.annotation.RepeatSubmit;
import com.aihna.common.log.annotation.Log;
import com.aihna.common.web.core.BaseController;
import com.aihna.common.mybatis.core.page.PageQuery;
import com.aihna.common.core.domain.R;
import com.aihna.common.core.validate.AddGroup;
import com.aihna.common.core.validate.EditGroup;
import com.aihna.common.log.enums.BusinessType;
import com.aihna.common.excel.utils.ExcelUtil;
import com.aihna.system.domain.vo.SysWechatConfigVo;
import com.aihna.system.domain.bo.SysWechatConfigBo;
import com.aihna.system.service.ISysWechatConfigService;
import com.aihna.common.mybatis.core.page.TableDataInfo;

/**
 * 微信配置
 *
 * @author Joseph.Chen
 * @date 2024-05-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/wechatConfig")
@Slf4j
public class SysWechatConfigController extends BaseController {

    private final ISysWechatConfigService sysWechatConfigService;

    /**
     * 初始化配置文件
     */
    @Bean
    public WxMaService wxMaService() {
        log.info("----------初始化微信配置----------");
        List<SysWechatConfigVo> configs = sysWechatConfigService.queryAll();

        WxMaService maService = new WxMaServiceImpl();
        maService.setMultiConfigs(
                configs.stream()
                        .map(a -> {
                            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
//                WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
                            // 使用上面的配置时，需要同时引入jedis-lock的依赖，否则会报类无法找到的异常
                            config.setAppid(a.getAppid());
                            config.setSecret(a.getSecret());
                            return config;
                        }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
        return maService;
    }


    /**
     * 查询微信配置列表
     */
    @SaCheckPermission("system:wechatConfig:list")
    @GetMapping("/list")
    public TableDataInfo<SysWechatConfigVo> list(SysWechatConfigBo bo, PageQuery pageQuery) {
        return sysWechatConfigService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出微信配置列表
     */
    @SaCheckPermission("system:wechatConfig:export")
    @Log(title = "微信配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysWechatConfigBo bo, HttpServletResponse response) {
        List<SysWechatConfigVo> list = sysWechatConfigService.queryList(bo);
        ExcelUtil.exportExcel(list, "微信配置", SysWechatConfigVo.class, response);
    }

    /**
     * 获取微信配置详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:wechatConfig:query")
    @GetMapping("/{id}")
    public R<SysWechatConfigVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(sysWechatConfigService.queryById(id));
    }

    /**
     * 新增微信配置
     */
    @SaCheckPermission("system:wechatConfig:add")
    @Log(title = "微信配置", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysWechatConfigBo bo) {
        return toAjax(sysWechatConfigService.insertByBo(bo));
    }

    /**
     * 修改微信配置
     */
    @SaCheckPermission("system:wechatConfig:edit")
    @Log(title = "微信配置", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysWechatConfigBo bo) {
        return toAjax(sysWechatConfigService.updateByBo(bo));
    }

    /**
     * 删除微信配置
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:wechatConfig:remove")
    @Log(title = "微信配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(sysWechatConfigService.deleteWithValidByIds(List.of(ids), true));
    }
}
